package com.dc.ai.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.dc.ai.common.datasource.DynamicDataSource;
import com.dc.ai.common.enums.DataSourceType;
import com.dc.ai.config.properties.DruidProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * druid 配置多数据源
 *
 * @author ruoyi
 */
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.master")
    public DataSource masterDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean
    @Qualifier("onlineDataSource")
    @ConfigurationProperties("spring.datasource.online")
    @ConditionalOnProperty(prefix = "spring.datasource.online", name = "enabled", havingValue = "true")
    public DataSource onlineDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean
    @Qualifier("checkDataSource")
    @ConfigurationProperties("spring.datasource.check")
    @ConditionalOnProperty(prefix = "spring.datasource.check", name = "enabled", havingValue = "true")
    public DataSource checkDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    // 创建动态数据源
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(
            @Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("onlineDataSource") DataSource onlineDataSource,
            @Qualifier("checkDataSource") DataSource offlineDataSource) {

        // 初始化目标数据源集合
        Map<Object, Object> targetDataSources = new HashMap<>();

        // 将主数据源放入动态数据源中
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);

        if (onlineDataSource != null) {
            targetDataSources.put(DataSourceType.ONLINE.name(), onlineDataSource);
        }

        if (offlineDataSource != null) {
            targetDataSources.put(DataSourceType.CHECK.name(), offlineDataSource);
        }

        // 创建并返回动态数据源
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}